//index.js
//获取应用实例
const app = getApp();
let api = require('../../utils/api.js');
var QQMapWX = require('../../public/js/qqmap-wx-jssdk.min.js');
Page({
  data: {
    titleTop: '', //区域离顶部的高度
    scrollTop: 0, //滑动条离顶部的距离
    currentIndex: 0,
    orderList: [], // 订单列表
    "firstList": [],
    "secondList": [],
    userLocationCity: "", // 用户当前所在城市
    background: [],
    pageNum: 1,
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    interval: 2000,
    duration: 500,
    Height: "",
    userStart: Number,
    commonRoutes: [],
    orderSwiperHeight: [],
    editIndex: 0,
    delBtnWidth: 180, //删除按钮宽度单位（rpx）
    userTotal: Number

  },
  // 登陆后能获取的数据
  getOnload() {
    var that = this;
    let token = wx.getStorageSync('TOKEN')
    let {
      userLocationCity,
      userLocationProvince
    } = app.globalData
    app.getUserInfo().then((res) => {
      that.saveLocationCity(userLocationCity, userLocationProvince);
      that.getUserRoute(token)
      app.getRemind()
    })
  },
  onShow() {
    this.setData({
      userLocationCity: app.globalData.userLocationCity
    })
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    var swiperHeight = [];
    swiperHeight.push(that.data.orderList.length * 148)
    that.setData({
      orderSwiperHeight: swiperHeight,
    });
    // 实例化腾讯地图SDK
    var qqmapsdk = new QQMapWX({
      key: 'NT2BZ-Y5Q34-YYCUF-DLQNZ-KW3L5-TCFCC' // 必填
    });
    if (app.globalData.userLocationCity.length <= 1) {
      wx.getLocation({
        // type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude;
          var longitude = res.longitude;
          // 向后台传递当前定位
          // that.saveLocation(latitude, longitude);
          // 调用接口
          // 2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: latitude,
              longitude: longitude
            },
            success: function (res) {
              app.globalData.userLocationCity = res['result']['address_component']['city'];
              app.globalData.userLocation = {
                latitude: latitude,
                longitude: longitude
              }
              app.globalData.userLocationProvince = res['result']['address_component']['province'];
              that.setData({
                userLocationCity: app.globalData.userLocationCity
              })
            }
          })
        }
      })
    }
    var that = this;
    var token = wx.getStorageSync('TOKEN');

    api._get('/banner/list/1', '', token).then(res1 => {
      // console.log(res1)
      if (res1.code == 200) {
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              background: res1.result,
              winWidth: res.windowWidth,
              winHeight: res.windowHeight - app.globalData.navHeight,
              pageNum: 1

            });
          }
        });
        api._get('/user/active/total', '', '').then(res2 => {
          if (res2.code == 200) {
            that.getOrderList(1, '');
            that.setData({
              userTotal: res2.result.total,
            });
          }
        });
      }
    })
    if (wx.getStorageSync('TOKEN')) {
      that.getOnload()
    }
  },
  onReady() {
    let that = this;

    //创建节点选择器
    var query = wx.createSelectorQuery();
    //选择id
    query.select('#title').boundingClientRect()
    query.exec(function (res) {
      //res就是 所有标签为mjltest的元素的信息 的数组
      //取高度
      that.setData({
        titleTop: (res[0].top) - (res[0].height),
        orderList: that.data.orderList
      })
    })
  },
  // 高度  滚动时触发
  scroll: function (res) {
    const _this = this;
    const top = res.detail.scrollTop;
    _this.setData({
      scrollTop: top
    });
  },
  changeIndicatorDots() {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },

  changeAutoplay() {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },

  intervalChange(e) {
    this.setData({
      interval: e.detail.value
    })
  },

  durationChange(e) {
    this.setData({
      duration: e.detail.value
    })
  },
  // 轮播图宽高自适应
  imgHeight: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    //等比设置swiper的高度。即 图片宽度 / 图片高度 = 屏幕宽度 / swiper高度 ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度。此处单位为 px，不能是 rpx。
    var swiperH = winWid * imgh / imgw + "px";
    this.setData({
      Height: swiperH //设置高度，此处不能加;
    })
  }, //swiper切换时会调用
  pagechange: function (e) {
    if ("touch" === e.detail.source) {
      let currentPageIndex = this.data.currentIndex
      currentPageIndex = (currentPageIndex + 1) % 5
      this.setData({
        currentIndex: currentPageIndex
      })
    }
  },
  //用户点击tab时调用
  titleClick: function (e) {
    let that = this;
    this.setData({
      //拿到当前索引并动态改变
      pageNum: 1,
      currentIndex: e.currentTarget.dataset.idx,
    })
    var token = wx.getStorageSync('TOKEN');
    if (e.currentTarget.dataset.idx == 0) {
      that.getOrderList(1, token);
    } else if (e.currentTarget.dataset.idx == 1) {
      that.getOrderList(2, token);
    }
  },
  // 订单详情
  openDetail: function (e) {
    var that = this;
    var state = that.checkState();
    if (state) {
      var route = that.checkRoute();
      if (route) {
        var inviteState = wx.getStorageSync('ACTIVESTATE');
        if (inviteState == 1) {
          var id = e.currentTarget.dataset.gid;
          wx.navigateTo({
            url: '../order/orderDetail/orderDetail?id=' + id
          })
        } else {
          wx.showToast({
            title: '您目前忙碌状态，无法查看订单详情',
            icon: 'none'
          })
        }

      }
    }
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    let data = app.touch._touchstart(e, this.data.commonRoutes)
    this.setData({
      commonRoutes: data
    })
  },

  //滑动事件处理
  touchmove: function (e) {
    let data = app.touch._touchmove(e, this.data.commonRoutes)
    this.setData({
      commonRoutes: data
    })
  },
  // 上传用户当前定位
  saveLocation: function (latitude, longitude) {
    var param = {
      "lat": latitude,
      "lng": longitude
    }
    var token = wx.getStorageSync('TOKEN');
    api._put('/location/push', param, token).then(res => {
      console.log(res);
    })
  },
  /**
   * 货源列表
   */
  getOrderList: function (type, token, param, loadMore) {
    var that = this;
    if (type == 1) {
      var listName = "firstlist"
    } else if (type == 2) {
      var listName = "secondList"
    }
    var params = {}
    if (param) {
      params = param
    } else {
      params = {
        pageNum: 1,
        pageSize: 5,
        type: type
      }
    }

    api._get('/await/order/list/' + type, params, token).then(res => {
      if (res.code == 200) {
        var list = res.result;
        list.forEach(function (value, index) {
          var createTime = value.createTime * 1000;
          list[index]['createTime'] = app.formatDate(createTime, 'YYYY-MM-DD H:m:s')

          var shipmentTime = value.shipmentTime.start * 1000;
          list[index]['showShipmentTime'] = app.formatDate(shipmentTime, 'MM月DD日');

          var arrivalTime = value.arrivalTime.start * 1000;
          list[index]['showArrivalTime'] = app.formatDate(arrivalTime, 'MM月DD日');
          if (value.freightWeight.max && value.freightWeight.min) {
            list[index]["showfreightWeight"] = value.freightWeight.min + '-' + value.freightWeight.max + '吨';
          } else if (value.freightWeight.max && !value.freightWeight.min) {
            list[index]["showfreightWeight"] = value.freightWeight.max + '吨';
          } else if (!value.freightWeight.max && value.freightWeight.min) {
            list[index]["showfreightWeight"] = value.freightWeight.min + '吨';
          }
        });
        if (loadMore) {
          if (param.pageNum <= res.page.totalPage) {
            var showData = [...that.data.orderList, ...list];
            that.setData({
              orderList: showData
            })
          } else {
            wx.showToast({
              title: '没有更多订单',
              icon: 'none',
            })
            return false
          }
        } else {
          that.setData({
            orderList: list
          })
        }
      }
    })
  },
  callExpert: function (e) {
    var phone = e.currentTarget.dataset.phone;
    app.callExpert(phone);
  },
  /**
   * 修改状态
   */
  switch1Change: function (e) {
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    var value = e.detail.value;
    var state = Number;
    if (value) {
      state = 1;
    } else {
      state = 0;
    }
    var param = {
      state: state
    }
    api._put('/chauffeur/edit', param, token).then(res => {
      if (res.code == 200) {
        that.setData({
          userStart: state
        })
        wx.setStorageSync('ACTIVESTATE', state);
        wx.showToast({
          title: '操作成功',
          icon: 'none'
        })
      } else if (res.code == 20000015) {
        that.setData({
          userStart: 0
        })
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none'
        })
      }
    })
  },
  /**
   * 获取常用路线
   */
  getUserRoute: function (token) {
    var that = this;
    api._get('/chauffeur/route/get', '', token).then(res => {
      if (res.code == 200) {
        var list = res.result
        if (list == null) {
          wx.removeStorage({
            key: 'VEHICLELEN',
            success: function (res) {},
          })
          wx.removeStorage({
            key: 'VEHICLEMODEL',
            success: function (res) {},
          })
          wx.removeStorage({
            key: 'VEHICLELOAD',
            success: function (res) {},
          })
          wx.removeStorage({
            key: 'VEHICLETYPE',
            success: function (res) {},
          })
          that.setData({
            commonRoutes: []
          });
        } else {
          for (var i = 0; i < list.length; i++) {
            list[i].txtStyle = "";
            list[i].isMove = false;
          }
          that.setData({
            commonRoutes: list
          });
        }
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none'
        })
      }
    })
  },
  /**
   * 删除常用路线
   */
  delAddress: function (e) {
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    var id = e.currentTarget.dataset.addressid;
    var routesKey = e.currentTarget.dataset.index;
    var param = {
      id
    };
    var routesData = that.data.commonRoutes;
    wx.showModal({
      title: '提示',
      content: '确认要删除此路线么？',
      success: (res) => {
        if (res.confirm) {
          api._delete('/chauffeur/route/delete/' + id, param, token).then(res => {
            if (res.code == 200) {
              routesData.splice(routesKey, 1)
              that.setData({
                commonRoutes: routesData
              });
              that.getUserRoute(token)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },
  /**
   * 添加常用路线
   */
  addRoute: function (e) {
    var that = this;
    var state = that.checkState();
    if (state) {
      if (that.data.commonRoutes.length < 5) {
        wx.navigateTo({
          url: '../order/createRute/createRute',
        })
      } else {
        wx.showToast({
          title: '已超过常用路线设置上线，请删除后再添加',
          icon: 'none',
          duration: 2000
        })
      }

    }
  },
  checkState: function () {
    var that = this;
    var state = wx.getStorageSync('STATE');
    if (!wx.getStorageSync('TOKEN')) {
      app.goAuthpPages()
    } else {
      if (state != 1) {
        if (state == -2) {
          wx.showToast({
            title: '您的账户已被停用,需要跟工作人员联系恢复功能',
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '您还没有通过认证，为了不影响您的使用，请及时认证',
            cancelText: '取消',
            confirmText: '确定',
            success(res) {
              if (res.cancel) {
                // 用户点击了取消属性的按钮
              } else if (res.confirm) {
                // 用户点击了确定属性的按钮
                wx.navigateTo({
                  url: '../user/authentication/authentication',
                })
              }
            }
          })
        }
      } else {
        return true;
      }
    }

  },

  /**
   * 上传城市名称
   */
  saveLocationCity(city, province) {
    var param = {
      "city": city,
      "province": province
    }
    var token = wx.getStorageSync('TOKEN');
    api._put('/location/city', param, token).then(res => {
      if (res.code == 200) {
        wx.switchTab({
          url: '../../index/index',
          success: function (e) {}
        })
      }
    })
  },
  /**
   * 判断是否添加常用路线
   */
  checkRoute: function () {
    var that = this;
    var route = that.data.commonRoutes
    if (route.length == 0) {
      wx.showModal({
        title: '提示',
        content: '您还没有添加常用路线',
        cancelText: '取消',
        confirmText: '确定',
        success(res) {
          if (res.cancel) {
            // 用户点击了取消属性的按钮
          } else if (res.confirm) {
            // 用户点击了确定属性的按钮
            wx.navigateTo({
              url: '../order/createRute/createRute',
            })
          }
        }
      })
    } else {
      return true;
    }
  },
  goto: function (e) {
    var url = e.currentTarget.dataset.url;
    if (url != '') {
      wx.navigateTo({
        url: '/pages/gotoUrl/index?url=' + url,
      })
    }

  },

  onRefresh: function (e) {
    var callback = e.detail;
    var that = this;

    var param = {
      pageNum: 1,
      pageSize: 5
    };
    that.setData({
      pageNum: 1
    })
    setTimeout(function () {

      var token = wx.getStorageSync('TOKEN');
      var currentIndex = that.data.currentIndex
      if (currentIndex == 0) {
        that.getOrderList(1, token);
      } else if (currentIndex == 1) {
        that.getOrderList(2, token);
      }
      callback.success();

    }, 3000)
  },

  onLoadMore: function (e) {
    var callback = e.detail;
    var that = this;
    var param = {
      pageNum: that.data.pageNum + 1,
      pageSize: 5
    };
    that.setData({
      pageNum: that.data.pageNum + 1
    })
    setTimeout(function () {
      var token = wx.getStorageSync('TOKEN');
      var currentIndex = that.data.currentIndex
      if (currentIndex == 0) {
        that.getOrderList(1, token, param, true);
      } else if (currentIndex == 1) {
        that.getOrderList(2, token, param, true);
      }
      callback.success();
    }, 3000)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res);
    if (res.from === 'button') {
      this.setData({
        showShareModelStatus: false
      })
    } else if (res.from === 'menu') {
    }
  }
})